import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api', // 使用相对路径，通过Vite代理
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加token
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  response => {
    const data = response.data
    // 统一字段名，处理后端返回的大写字段名
    return {
      ...data,
      code: data.Code || data.code,
      msg: data.Msg || data.msg,
      value: data.Value || data.value
    }
  },
  error => {
    console.log('API响应拦截器错误:', error)
    if (error.response?.status === 401) {
      console.log('401错误，清除token')
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      // 只有在非登录页面才跳转
      if (window.location.pathname !== '/login') {
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)

// 认证相关API
export const authAPI = {
  // 用户登录
  login: (data) => {
    return api.post('/auth/login', {
      account: data.username,
      password: data.password
    })
  },

  // 用户注册
  register: (data) => {
    return api.post('/auth/register', {
      account: data.username,
      password: data.password,
      defaultRole: data.defaultRole || 'User',
      displayName: data.displayName,
      phone: data.phone,
      email: data.email
    })
  },

  // 获取用户信息
  getUserInfo: () => {
    return api.get('/user/profile')
  },

  // 退出登录
  logout: () => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }
}

// 仪表板相关API
export const dashboardAPI = {
  // 获取统计数据
  getStatistics: () => {
    return api.get('/Dashboard/statistics')
  },

  // 获取图表数据
  getChartData: () => {
    return api.get('/Dashboard/chart-data')
  },

  // 获取最近登录
  getRecentLogins: () => {
    return api.get('/Dashboard/recent-logins')
  }
}

export default api
